package com.njcb.ams.store.mail;

import com.njcb.ams.factory.domain.AppContext;
import com.njcb.ams.store.mail.bean.Email;
import com.njcb.ams.store.mail.bean.MultipartFile;
import com.njcb.ams.support.exception.ExceptionUtil;
import com.njcb.ams.util.AmsStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 邮件发送
 * 
 * @author liuyanlong
 *
 */
public class MailServiceManager implements IMailServiceManager {
	private static final Logger logger = LoggerFactory.getLogger(MailServiceManager.class);
	private StringBuffer message = new StringBuffer();
	private JavaMailSender mailSender = null;
	private TaskExecutor taskExecutor = null;

	public static MailServiceManager getInstance() {
		return (MailServiceManager) AppContext.getBean("mailServiceManager");
	}

	@Override
	public void sendMail(Email email) {
		if(null == mailSender){
			return;
		}
		if (null == email.getAddress() || email.getAddress().length == 0) {
			this.message.append("没用收件人");
			return;
		}
		// 收件人多于5时采用异步发送
		if (email.getAddress().length > 5) {
			sendMailByAsynchronousMode(email);
			this.message.append("采用异步发送邮件中……");
		} else {
			try {
				sendMailBySynchronizationMode(email);
			} catch (MessagingException e) {
				e.printStackTrace();
				ExceptionUtil.throwAppException(e.getMessage());
			}
			this.message.append("采用同步发送邮件中……");
		}
	}

	@Override
	public void sendMailByAsynchronousMode(final Email email) {
		taskExecutor.execute(new Runnable() {
			@Override
			public void run() {
				try {
					sendMailBySynchronizationMode(email);
				} catch (Exception e) {
					logger.error(e.getMessage());
				}
			}
		});
	}

	@Override
	public void sendMailBySynchronizationMode(Email email) throws MessagingException {
		MimeMessage mime = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(mime, true, "utf-8");
		helper.setFrom("admin@trythis.cn");
		helper.setTo(email.getAddress());
		// 密送
		helper.setBcc("23562656@qq.com");

		if (AmsStringUtils.hasLength(email.getCc())) {
			String[] cc = email.getCc().split(";");
			helper.setCc(cc);
		}
		// 回复到：
		helper.setReplyTo("23562656@qq.com");
		helper.setSubject(email.getSubject());
		// true表示设置为html格式
		helper.setText(email.getContent(), true);

		// 内嵌资源（很少用，先大部分资源为网络资源，邮件正文加URL即可）
		// helper.addInline("logo", new ClassPathResource("logo.gif"));

		// 处理附件
		for (MultipartFile file : email.getAttachment()) {
			if (null == file || file.isEmpty()) {
				continue;
			}
			String fileName = file.getOriginalFileName();
			try {
				fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
			} catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
			helper.addAttachment(fileName, new ByteArrayResource(file.getBytes()));
		}

		mailSender.send(mime);
	}

	public StringBuffer getMessage() {
		return message;
	}

	public void setMessage(StringBuffer message) {
		this.message = message;
	}

	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	public void setTaskExecutor(TaskExecutor taskExecutor) {
		this.taskExecutor = taskExecutor;
	}

}
